import {ChooseImageResult, FileSystem} from "./index";
import Taro from "@tarojs/taro"
import ImageFile = Taro.chooseImage.ImageFile;

export class H5FileSystem implements FileSystem {

  toBase64(file: ImageFile): Promise<string> {
    let successCallback;
    let errorCallback;
    const result = new Promise<string>((resolve, reject) => {
      successCallback = resolve
      errorCallback = reject
    });
    const fileReader = new FileReader();
    fileReader.onload = (e) => {
      successCallback(e.target?.result)
    }
    fileReader.onerror = (result) => {
      errorCallback(result)
    }
    fileReader.readAsDataURL(file.originalFileObj as any)
    return result
  }

  async toChooseImage(option: Taro.chooseImage.Option) {
    let result = await Taro.chooseImage(option);
    const resultBase64: ChooseImageResult[] = [];
    for (let tempFile of result.tempFiles) {
      let base64 = await this.toBase64(tempFile);
      resultBase64.push({imageFile: tempFile, base64})
    }
    return resultBase64
  }

  chooseImage(option: Taro.chooseImage.Option): Promise<ChooseImageResult[]> {
    return this.toChooseImage(option)
  }
}
